package com.example.eamh2system.netty.handler;

import com.digitalpetri.modbus.ModbusPdu;
import com.digitalpetri.modbus.codec.ModbusTcpPayload;
import com.digitalpetri.modbus.requests.ModbusRequest;
import com.example.eamh2system.netty.H2NettyClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@ChannelHandler.Sharable
public class H2IdleStateTrigger extends ChannelInboundHandlerAdapter {
    @Autowired
    private H2NettyClient h2NettyClient;


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
//                    sendHeartBeat(ctx);
                    break;
                case READER_IDLE:
                    log.info("心跳检测失败,连接重新建立中.....");
                    h2NettyClient.doConnect();
                    break;
                default:
                    break;
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    private void sendHeartBeat(ChannelHandlerContext ctx) {
        ByteBuf byteBuf = Unpooled.buffer();
        String contentLengt="hello,server";
        byteBuf.writeBytes(contentLengt.getBytes());

        if (ctx.channel().isActive()) {
            ctx.writeAndFlush(byteBuf);
//                ctx.writeAndFlush(protocol);
            log.info("心跳信息发送成功：{}", ctx.channel().remoteAddress());
        } else {
            log.info("心跳信息发送失败：{}", ctx.channel().remoteAddress());
        }
    }
}
